<template>
  <div class="upload-container">
    <!-- 简化的页面标题 -->
    <div class="page-header">
      <h1>上传医学影像文件</h1>
      <el-button type="primary" size="medium" icon="el-icon-back" @click="$router.push('/patients')">
        返回列表
      </el-button>
    </div>
    
    <!-- 步骤指引 -->
    <el-steps :active="currentStep" finish-status="success" simple class="upload-steps">
      <el-step title="选择文件" icon="el-icon-folder-opened"></el-step>
      <el-step title="上传文件" icon="el-icon-upload"></el-step>
      <el-step title="完成" icon="el-icon-check"></el-step>
    </el-steps>
    
    <!-- 步骤1: 选择文件 -->
    <div v-if="currentStep === 1" class="step-container">
      <!-- 简化的上传区域 -->
      <div class="upload-area" 
           @dragover.prevent="onDragOver" 
           @dragleave.prevent="onDragLeave" 
           @drop.prevent="onDrop"
           @click="triggerFileInput"
           :class="{ 'drag-over': isDragOver }">
        <i class="el-icon-upload"></i>
        <div class="upload-text">
          <strong>点击此处选择文件</strong>
          <div class="upload-subtext">或将文件拖放到这里</div>
        </div>
        <input 
          type="file" 
          ref="fileInput" 
          style="display: none" 
          multiple 
          @change="onFileChange"
          accept=".dcm,.dicom,application/dicom"
        >
      </div>
      
      <!-- 简化的文件列表 -->
      <div v-if="uploadFiles.length > 0" class="selected-files">
        <div class="files-header">
          <span>已选择 {{ uploadFiles.length }} 个文件</span>
          <el-button type="text" @click="clearFiles" size="small">清空</el-button>
        </div>
        <div class="files-preview">
          <div v-for="(file, index) in displayFiles" :key="index" class="file-item-simple">
            <i class="el-icon-document"></i>
            <span class="file-name-simple" :title="file.name">{{ file.name }}</span>
          </div>
          <div v-if="uploadFiles.length > 5" class="more-files">
            还有 {{ uploadFiles.length - 5 }} 个文件...
          </div>
        </div>
        <div class="next-step">
          <el-button type="primary" size="medium" @click="goToUpload" :disabled="uploadFiles.length === 0">
            开始上传 <i class="el-icon-arrow-right"></i>
          </el-button>
        </div>
      </div>
      
      <!-- 简化的提示 -->
      <div class="simple-tips" v-if="uploadFiles.length === 0">
        <ul>
          <li><i class="el-icon-info"></i> 支持 DICOM 格式的医学影像文件</li>
          <li><i class="el-icon-info"></i> 可以一次选择多个文件</li>
        </ul>
      </div>
    </div>
    
    <!-- 步骤2: 上传文件 -->
    <div v-if="currentStep === 2" class="step-container">
      <!-- 简化的进度显示 -->
      <div class="upload-progress-container">
        <div class="progress-header">
          <span class="progress-title">正在上传文件...</span>
          <span class="progress-count">{{ uploadedCount }}/{{ totalFiles }}</span>
        </div>
        
        <!-- 大号进度条 -->
        <el-progress 
          :percentage="totalProgress"
          :color="progressColor"
          :stroke-width="24"
          class="big-progress">
        </el-progress>
        
        <!-- 简化的状态显示 -->
        <div class="upload-status-simple">
          <div v-if="isUploading" class="status-message uploading">
            <i class="el-icon-loading"></i> 正在上传，请稍候...
          </div>
          <div v-else-if="failedCount > 0" class="status-message error">
            <i class="el-icon-error"></i> {{ failedCount }} 个文件上传失败
          </div>
          <div v-else-if="uploadedCount === totalFiles && totalFiles > 0" class="status-message success">
            <i class="el-icon-success"></i> 上传完成！
          </div>
        </div>
        
        <!-- 简化的控制按钮 -->
        <div class="upload-controls-simple">
          <el-button 
            v-if="isUploading"
            type="danger" 
            size="medium"
            @click="cancelUpload">
            取消上传
          </el-button>
          <el-button 
            v-if="!isUploading && (uploadedCount < totalFiles || failedCount > 0)"
            type="primary" 
            size="medium"
            @click="retryUpload">
            重试上传
          </el-button>
          <el-button 
            v-if="!isUploading && uploadedCount > 0"
            type="success" 
            size="medium"
            @click="goToComplete">
            完成 <i class="el-icon-arrow-right"></i>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 步骤3: 完成 -->
    <div v-if="currentStep === 3" class="step-container">
      <div class="completion-container">
        <div class="completion-icon">
          <i class="el-icon-success"></i>
        </div>
        <h2 class="completion-title">上传完成！</h2>
        <p class="completion-message">
          成功上传了 {{ uploadedCount }} 个文件
          <span v-if="failedCount > 0" class="error-text">
            ({{ failedCount }} 个文件失败)
          </span>
        </p>
        
        <div class="completion-actions">
          <el-button 
            type="primary" 
            size="medium"
            @click="$router.push('/patients')">
            <i class="el-icon-view"></i> 查看患者列表
          </el-button>
          <el-button 
            type="default" 
            size="medium"
            @click="resetUpload">
            <i class="el-icon-refresh"></i> 上传更多文件
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { orthancApi } from '@/services/orthanc'

export default {
  name: 'UploadPage',
  data() {
    return {
      currentStep: 1,
      uploadFiles: [],
      isDragOver: false,
      isUploading: false,
      uploadedCount: 0,
      failedCount: 0,
      totalFiles: 0,
      uploadStartTime: null,
      uploadSpeed: '',
      uploadInterval: null,
      concurrentUploads: 3, // 减少并发数，适合低配置电脑
      chunkSize: 1 * 1024 * 1024, // 减小分块大小 (1MB)
      uploadQueue: [],
      processingCount: 0,
      isPaused: false,
      showCompletionGuide: false
    }
  },
  computed: {
    totalProgress() {
      if (this.totalFiles === 0) return 0
      return Math.floor((this.uploadedCount / this.totalFiles) * 100)
    },
    progressColor() {
      if (this.failedCount > 0) return '#F56C6C'
      if (this.uploadedCount === this.totalFiles && this.totalFiles > 0) return '#67C23A'
      return '#409EFF'
    },
    // 只显示前5个文件
    displayFiles() {
      return this.uploadFiles.slice(0, 5)
    }
  },
  methods: {
    // 触发文件选择
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    
    // 拖拽相关方法
    onDragOver() {
      this.isDragOver = true
    },
    onDragLeave() {
      this.isDragOver = false
    },
    onDrop(event) {
      this.isDragOver = false
      this.handleFiles(event.dataTransfer.files)
    },
    
    // 文件选择处理
    onFileChange(event) {
      this.handleFiles(event.target.files)
      // 重置文件输入，允许重复选择相同文件
      event.target.value = ''
    },
    
    // 处理选择的文件
    handleFiles(fileList) {
      // 转换为数组并过滤
      const files = Array.from(fileList).filter(file => {
        // 只接受 DICOM 文件
        return file.name.endsWith('.dcm') || 
               file.name.endsWith('.dicom') || 
               file.type === 'application/dicom'
      })
      
      if (files.length === 0) {
        this.$message.warning('请选择有效的 DICOM 文件')
        return
      }
      
      // 添加到文件列表
      const newFiles = files.map(file => ({
        file,
        name: file.name,
        size: file.size,
        status: '等待中',
        progress: 0,
        error: null
      }))
      
      this.uploadFiles = [...this.uploadFiles, ...newFiles]
    },
    
    // 清空文件列表
    clearFiles() {
      if (this.isUploading) {
        this.$message.warning('上传过程中无法清空文件列表')
        return
      }
      this.uploadFiles = []
    },
    
    // 进入上传步骤
    goToUpload() {
      this.currentStep = 2
      this.totalFiles = this.uploadFiles.length
      this.startUpload()
    },
    
    // 进入完成步骤
    goToComplete() {
      this.currentStep = 3
    },
    
    // 重置上传
    resetUpload() {
      this.currentStep = 1
      this.uploadFiles = []
      this.uploadedCount = 0
      this.failedCount = 0
      this.totalFiles = 0
      this.isUploading = false
      clearInterval(this.uploadInterval)
    },
    
    // 重试上传
    retryUpload() {
      // 重置失败文件状态
      this.uploadFiles.forEach(file => {
        if (file.status === '失败') {
          file.status = '等待中'
          file.progress = 0
          file.error = null
        }
      })
      
      this.failedCount = 0
      this.startUpload()
    },
    
    // 开始上传
    async startUpload() {
      if (this.isUploading) return
      
      this.isUploading = true
      this.uploadStartTime = Date.now()
      
      try {
        // 初始化上传队列 - 只包含等待中的文件
        this.uploadQueue = this.uploadFiles.filter(file => file.status === '等待中')
        this.processingCount = 0
        
        // 启动并发上传
        await this.processQueue()
        
        console.log('所有文件上传完成')
      } catch (error) {
        console.error('上传过程中发生错误:', error)
      } finally {
        this.isUploading = false
        clearInterval(this.uploadInterval)
      }
    },
    
    // 处理上传队列
    async processQueue() {
      if (this.isPaused) return
      
      // 如果队列为空且没有正在处理的文件，则完成
      if (this.uploadQueue.length === 0 && this.processingCount === 0) {
        return
      }
      
      // 填充并发槽位
      while (this.processingCount < this.concurrentUploads && this.uploadQueue.length > 0 && !this.isPaused) {
        const file = this.uploadQueue.shift()
        this.processingCount++
        
        // 不使用 await，让上传并行进行
        this.uploadFile(file).finally(() => {
          this.processingCount--
          // 继续处理队列
          this.processQueue()
        })
      }
    },
    
    // 上传单个文件
    async uploadFile(file) {
      // 更新文件状态
      file.status = '上传中'
      
      try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file.file)
        
        // 使用 axios 实例直接发送请求
        await orthancApi.post('/instances', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          // 添加上传进度回调
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            file.progress = percentCompleted
          }
        })
        
        // 上传成功
        file.status = '成功'
        this.uploadedCount++
      } catch (error) {
        console.error(`上传文件 ${file.name} 失败:`, error)
        file.status = '失败'
        file.error = error.message || '上传失败'
        this.failedCount++
      }
    },
    
    // 取消上传
    cancelUpload() {
      this.isUploading = false
      this.isPaused = false
      clearInterval(this.uploadInterval)
      
      // 更新所有未完成文件的状态
      this.uploadFiles.forEach(file => {
        if (file.status === '上传中' || file.status === '等待中') {
          file.status = '已取消'
        }
      })
      
      // 清空上传队列
      this.uploadQueue = []
      this.processingCount = 0
    }
  }
}
</script>

<style>
.upload-container {
  max-width: 960px;
  margin: 0 auto;
  padding: 15px;
  font-size: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
}

.upload-steps {
  margin-bottom: 25px;
}

.step-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

/* 上传区域样式 */
.upload-area {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100px;
  border: 2px dashed #409EFF;
  border-radius: 6px;
  cursor: pointer;
  background-color: #f0f9ff;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.upload-area:hover {
  background-color: #ecf5ff;
}

.upload-area.drag-over {
  background-color: #ecf5ff;
  border-color: #66b1ff;
}

.upload-area i {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 10px;
}

.upload-text {
  text-align: center;
}

.upload-subtext {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

/* 文件列表样式 */
.selected-files {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.files-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.files-preview {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px 15px;
}

.file-item-simple {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.file-item-simple i {
  color: #909399;
  margin-right: 8px;
}

.file-name-simple {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.more-files {
  padding: 5px 0;
  color: #909399;
  font-style: italic;
  text-align: center;
}

.next-step {
  padding: 15px;
  text-align: center;
  border-top: 1px solid #ebeef5;
}

/* 简化提示样式 */
.simple-tips {
  margin-top: 20px;
}

.simple-tips ul {
  padding-left: 0;
  list-style-type: none;
}

.simple-tips li {
  margin-bottom: 10px;
  color: #606266;
}

.simple-tips i {
  color: #409EFF;
  margin-right: 5px;
}

/* 上传进度样式 */
.upload-progress-container {
  padding: 20px 0;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.progress-title {
  font-size: 18px;
  font-weight: bold;
}

.progress-count {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.big-progress {
  margin-bottom: 20px;
}

.big-progress .el-progress-bar__outer {
  border-radius: 12px;
}

.upload-status-simple {
  margin: 20px 0;
  text-align: center;
}

.status-message {
  font-size: 18px;
  padding: 10px;
  border-radius: 4px;
}

.status-message i {
  margin-right: 5px;
}

.status-message.uploading {
  color: #409EFF;
}

.status-message.error {
  color: #F56C6C;
}

.status-message.success {
  color: #67C23A;
}

.upload-controls-simple {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

/* 完成页面样式 */
.completion-container {
  text-align: center;
  padding: 30px 0;
}

.completion-icon {
  font-size: 64px;
  color: #67C23A;
  margin-bottom: 20px;
}

.completion-title {
  font-size: 24px;
  margin-bottom: 15px;
}

.completion-message {
  font-size: 18px;
  margin-bottom: 30px;
}

.error-text {
  color: #F56C6C;
}

.completion-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 响应式调整 */
@media screen and (max-width: 1024px) {
  .upload-container {
    padding: 10px;
  }
  
  .page-header h1 {
    font-size: 20px;
  }
  
  .upload-area {
    height: 80px;
  }
  
  .upload-area i {
    font-size: 24px;
  }
  
  .files-preview {
    max-height: 150px;
  }
  
  .progress-title, .progress-count {
    font-size: 16px;
  }
  
  .status-message {
    font-size: 16px;
  }
  
  .completion-icon {
    font-size: 48px;
  }
  
  .completion-title {
    font-size: 20px;
  }
  
  .completion-message {
    font-size: 16px;
  }
}
</style> 